package com.datang.yourtomcat01;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-09-16 15:50
 * @notify 服务端程序
 * @version 1.0
 */
public class HttpServer {
    //C:\workspace\yourTomcat\src   /webroot
    public static final String WEB_ROOT = System.getProperty("user.dir")+ File.separator+ "webroot";

    //停止语句
    private static final String SHUTDOWN_COMMAND="/SHUTDOWN";
    //停止标识符
    private boolean shutdown = false;

    /*
     * @author 顶风少年
     * @date 2019/9/16 16:57
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @result void
     * @notify 监听请求
     * version 1.0
     */

    public void await(){
        ServerSocket serverSocket = null;
        int port = 8080;
        try{
            //创建服务端
            serverSocket = new ServerSocket(port,1, InetAddress.getByName("127.0.0.1"));
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }

        //循环监听
        while (!shutdown){
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                //客户端发送请求这里则会监听到
                socket = serverSocket.accept();
                //获取输入流
                input = socket.getInputStream();
                //获取输出流
                output = socket.getOutputStream();
                //解析请求对象
                Request request = new Request(input);
                request.parse();
                //创建相应对象
                Response response = new Response(output);
                response.setRequest(request);
                response.sendStaticResource();
                //关闭socket通道
                socket.close();
                //如果客户端传递的停止则,更改监听标记
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            }catch (Exception e){
                e.printStackTrace();
                continue;
            }

        }
    }
}
